package com.youlai.mybatis.service;

import com.youlai.mybatis.domain.SysUser;
import com.youlai.mybatis.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author zc
 * @date 2023-03-19 22:26
 */
@Slf4j
@Component
public class SysUserService {


    @Resource
    private SysUserMapper sysUserMapper;
    /**
     *
     * @param sysUser
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW,rollbackFor = RuntimeException.class,isolation = Isolation.READ_COMMITTED)
    public void updateError(SysUser sysUser){
        log.info("开始修改");
        sysUser.setNickname("修改后"+sysUser.getNickname());
        sysUserMapper.updateByPrimaryKey(sysUser);
        log.info("修改完成");
        try {
            Thread.sleep(2000);
            log.info("开始回滚");
            throw new RuntimeException("An error has occurred.");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 开启一个新事务,演示不可重复读
     * @param sysUser
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void updateSysUser(SysUser sysUser) {
        sysUser.setNickname("修改后"+sysUser.getNickname());
        sysUserMapper.updateByPrimaryKey(sysUser);
    }

    /**
     * 删除幻读数据
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW,isolation = Isolation.READ_COMMITTED)
    public void resetSysUser(int startId, int endId){
        for (long i = startId; i < endId-5; i++) {
            sysUserMapper.deleteByPrimaryKey(i);
        }
    }

    /**
     *添加幻读数据
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW,isolation = Isolation.READ_COMMITTED)
    public void addSysUser(int startId, int endId){
        log.info("添加数据");
        for (Integer i = startId; i < endId-5; i++) {
            SysUser sysUser = new SysUser();
            sysUser.setId(i);
            sysUser.setNickname("幻读用户"+i);
            sysUser.setUsername("幻读用户"+i);
            sysUserMapper.insert(sysUser);
        }
    }

    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.REPEATABLE_READ)
    public List<SysUser> getUsers(int startId, int endId){
        List<SysUser> usersByIdRange = sysUserMapper.getUsersByIdRange(startId, endId);
        return usersByIdRange;
    }
}
